package Netty.protobuf;

import Netty.protobuf.protoClass.Message;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyServer {

    public void start(int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);  //boss线程组,接收传入的连接，并将连接分配给worker线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup)
                     .channel(NioServerSocketChannel.class)      //在这里，我们指定使用NioServerSocketChannel类来实例化一个新的Channel(通道)来接受传入的连接。
                     .childHandler(new ChannelInitializer<SocketChannel>() {  //设置服务器处理程序
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ProtobufVarint32FrameDecoder()); //解决粘包拆包
                            ch.pipeline().addLast("decoder", new ProtobufDecoder(Message.MessageProto.getDefaultInstance()));//protobuf编码器
                            ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());//解决粘包半包编码器
                            ch.pipeline().addLast("encoder", new ProtobufEncoder());//protobuf解码器
                            ch.pipeline().addLast(new NettyServerHandler()); //自定义handler
                        };
                     })
                     .option(ChannelOption.SO_BACKLOG, 128)
                     .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture future = bootstrap.bind(port).sync();    //启动服务器
            System.out.println("netty Server port : " + port );
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {

        new NettyServer().start(8081);
    }
}